import sqlite3
import logging
import threading
from contextlib import contextmanager
from queue import Queue, Empty
from threading import Lock

class DatabaseManager:
    def __init__(self, db_path, min_connections=1, max_connections=5, timeout=30):
        self.db_path = db_path
        self.min_connections = min_connections
        self.max_connections = max_connections
        self.timeout = timeout
        self.thread_local = threading.local()
        self.lock = Lock()

    def _get_thread_connection(self):
        """获取当前线程的数据库连接"""
        if not hasattr(self.thread_local, 'connection'):
            self.thread_local.connection = sqlite3.connect(self.db_path)
        return self.thread_local.connection

    @contextmanager
    def get_connection(self):
        """获取数据库连接的上下文管理器"""
        conn = None
        try:
            conn = self._get_thread_connection()
            yield conn
        except Exception as e:
            logging.error(f"获取数据库连接失败: {str(e)}")
            raise

    def execute_query(self, query, params=None):
        """执行查询操作"""
        with self.get_connection() as conn:
            try:
                cursor = conn.cursor()
                if params:
                    cursor.execute(query, params)
                else:
                    cursor.execute(query)
                result = cursor.fetchall()
                conn.commit()
                return result
            except Exception as e:
                logging.error(f"执行查询失败: {str(e)}")
                conn.rollback()
                raise
            finally:
                cursor.close()

    def execute_update(self, query, params=None):
        """执行更新操作"""
        with self.get_connection() as conn:
            try:
                cursor = conn.cursor()
                if params:
                    cursor.execute(query, params)
                else:
                    cursor.execute(query)
                conn.commit()
            except Exception as e:
                logging.error(f"执行更新失败: {str(e)}")
                conn.rollback()
                raise
            finally:
                cursor.close()

    def close_all(self):
        """关闭所有连接"""
        if hasattr(self.thread_local, 'connection'):
            try:
                self.thread_local.connection.close()
                del self.thread_local.connection
            except Exception as e:
                logging.error(f"关闭连接失败: {str(e)}")